<template>
    <el-form-item :label="props.label" :prop="props.prop" :width="props.width">
        <template #label>
            <span>{{ props.label }}</span>
            <span class="tip" v-if="props.tip">
                <el-tooltip effect="dark" :content="props.tip" placement="top">
                    <i class="fa fa-question-circle"></i>
                </el-tooltip>
            </span>
        </template>
        <el-input-number class="input-number" v-model="state.value" :controls-position="'right'" v-bind="props.inputAttr" @change="handleChange" />
        <div class="help-block" v-if="props.blockHelp">{{ props.blockHelp }}</div>
    </el-form-item>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'

const props = withDefaults(
    defineProps<{
        label: string
        prop?: string
        inputAttr?: {
            step?: number
            precision?: number
            min?: number
            max?: number
            placeholder?: string
            readonly?: boolean
            [key: string]: any
        }
        modelValue: string | number | undefined | null
        tip?: string
        blockHelp?: string
        width?: string | number
    }>(),
    {
        inputAttr: () => ({
            step: 1,
            min: 0,
        }),
    }
)
const state = reactive<{
    value: any
}>({
    value: props.modelValue === undefined ? undefined : Number(props.modelValue),
})

const emits = defineEmits(['update:modelValue', 'change'])

const handleChange = (value: any) => {
    emits('change', value)
}

watch(
    () => props.modelValue,
    (newVal) => {
        state.value = newVal == null ? newVal : Number(newVal)
    }
)
watch(
    () => state.value,
    (newVal) => {
        emits('update:modelValue', newVal)
    }
)
</script>

<style scoped lang="scss">
.input-number {
    width: 100%;
}

:deep(.el-input__inner) {
    text-align: left;
}

.help-block {
    width: 100%;
    margin-top: 5px;
    font-size: 13px;
    line-height: 16px;
    color: #999;
}

.tip {
    padding-left: 6px;
    color: var(--el-text-color-secondary);
    i {
        cursor: pointer;
    }
}
</style>
